package controllers;

import helpers.UrlHelper;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
import com.google.appengine.api.files.GSFileOptions.GSFileOptionsBuilder;
import com.google.appengine.api.urlfetch.FetchOptions;
import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;

public class ExampleGetImage extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		String url = (String) request.getParameter("url");
		String regTitle = "#page .post .postmetadata h1";
		String regContent = "#page .post .entry";
		if (url == null || url.isEmpty()) {
			url = "http://iphone.appstorm.net/reviews/games-reviews/max-payne-mobile-story-driven-shoot-em-up/";
		}
		ArrayList<String> imgs = new ArrayList<String>();
		ArrayList<String> new_imgs = new ArrayList<String>();
		
		try {
			Document doc = Jsoup.connect(url).get();
			String title = doc.select(regTitle).html();
			String content = doc.select(regContent).html();
			Elements elms = doc.select(regContent).select("img");
			for (int i = 0; i < elms.size(); i++) {
				String src = elms.get(i).attr("src");
				String name = UrlHelper.getName(src);
				imgs.add(src);
				getFile(src, name);
				content = content.replace(src, "http://static.1streview.org/" + name);
			}
			response.getWriter().println(title);
			response.getWriter().println(content);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public void getFile(String urlString, String fileName) throws IOException {
		String BUCKETNAME = "static.1streview.org";
		
		byte[] img = null;
		URLFetchService fetchService =
            URLFetchServiceFactory.getURLFetchService();
		// Fetch the image at the location given by the url query string parameter
		URL url = new URL(urlString);
		// Fetch the image at the location given by the url query string parameter
		FetchOptions fetchOptions =FetchOptions.Builder.withDefaults();
		fetchOptions.setDeadline((double)30*60);
		HTTPRequest request = new HTTPRequest(url, HTTPMethod.GET, fetchOptions);
        HTTPResponse fetchResponse = fetchService.fetch(request);
        
        String fetchResponseContentType = null;
        for (HTTPHeader header : fetchResponse.getHeaders()) {
            // For each request header, check whether the name equals
            // "Content-Type"; if so, store the value of this header
            // in a member variable
            if (header.getName().equalsIgnoreCase("content-type")) {
                fetchResponseContentType = header.getValue();
                break;
            }
        }
        if (fetchResponseContentType != null) {
        	img = (byte[]) fetchResponse.getContent();
        	
        	FileService fileService = FileServiceFactory.getFileService();
		    GSFileOptionsBuilder optionsBuilder = new GSFileOptionsBuilder()
		       .setBucket(BUCKETNAME)
		       .setKey(fileName)
		       .setMimeType(fetchResponseContentType)
		       .setAcl("public_read").setCacheControl("public, max-age=6000");
		       
		    
		    AppEngineFile writableFile =
		        fileService.createNewGSFile(optionsBuilder.build());
		    // Open a channel to write to it
		    boolean lock = true;
		    FileWriteChannel writeChannel =
		        fileService.openWriteChannel(writableFile, lock);
		 
		    // This time we write to the channel using standard Java
		    writeChannel.write(java.nio.ByteBuffer.wrap(img));
		    // Now finalize
		    writeChannel.closeFinally();
		    System.out.println("Done writing...");
		    
        }
	}
}
